<template>
	<view class="template">
		<view v-if="!pubTplList.length" class="empty">当前还没有公共模板</view>
		<view v-else>
			<view style="font-size: 18px;">公共模板列表：</view>
			<view class="tplList"
				v-for="(pubTplListVal, pubTplListIdx) in pubTplList"
				:key="pubTplListIdx">
				<navigator :url="'../template/tpl_review?tpl_id='+pubTplListVal._id">{{pubTplListVal.name}}</navigator>
				<button class="mini" @click="insertTpl(pubTplListVal._id)">收藏</button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				pubTplList: []
			}
		},
		created() {
			this.getPubTplList();
		},
		methods: {
			getPubTplList() {
				uniCloud.callFunction({
					name: "ha_get_pub_tpl",
					data: {
						uid: uni.getStorageSync("uid")
					},
					success: ({result}) => {
						// console.log(result);

						this.pubTplList = result;
					},
					fail() {
						uni.showToast({
							icon: 'none',
							title: '网络异常，请稍后重试！'
						});
					}
				});
			},
			insertTpl(tpl_id) {
				// console.log(tpl_id);

				uniCloud.callFunction({
					name: "ha_add_my_tpl",
					data: {
						uid: uni.getStorageSync("uid"),
						tpl_id,
						get_way: 1
					},
					success: ({result}) => {
						// console.log(result);

						if ( result.status === 0 ) {
							uni.showToast({
								title: `${result.msg || "收藏成功！"}`,
								duration: 1000
							});
						} else if (result.status === -1) {
							uni.showToast({
								icon: "none",
								title: `${result.msg || "网络异常，请稍后重试！"}`,
								duration: 1000,
								success() {
									uni.redirectTo({
										url: "/pages/user/user_login"
									})
								}
							});
						} else {
							uni.showToast({
								icon: 'none',
								title: `${result.msg || "网络异常，请稍后重试！"}`,
								duration: 1000
							});
						}
					},
					fail() {
						uni.showToast({
							icon: 'none',
							title: '网络异常，请稍后重试！'
						});
					}
				});
			}
		}
	}
</script>

<style>

	.tplList {
		justify-content: space-between;
		width: 90%;
		display: flex;
		margin: 10rpx 0;
	}

	.tplList navigator {
		margin-left: 20rpx;
	}

	.tplList button {
		margin-right: 10rpx;
	}
</style>
